package com.gjzhao.fmmall.config.myfilter;

import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Description: 自定义服务过滤器-针对某个具体的微服务设置过滤器
 * @Author: gjzhao
 * @Date Created in 2022-02-17 9:29 下午
 */
public class MyFilter implements GatewayFilter, Ordered { //实现gateway提供的过滤器、执行顺序

    private Logger logger = LoggerFactory.getLogger(getClass());

    //过滤行为
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        logger.info("--------进入服务过滤器");

        List<String> list = exchange.getRequest().getQueryParams().get("user");

        if (list != null && list.size() > 0) {

            String userValue = list.get(0);

            logger.info("-----当前请求参数user:{}", userValue);

            return chain.filter(exchange);
        } else {

            logger.info("-----当前请求参数中未携带指定参数user----");

            ServerHttpResponse response = exchange.getResponse();
            //设置响应头
            response.getHeaders().add("Content-Type", "application/json;charset=utf-8");
            //设置状态码
            response.setStatusCode(HttpStatus.BAD_REQUEST);
            // 封装响应数据
            String str = "未正确携带参数";
            DataBuffer dataBuffer = response.bufferFactory().wrap(str.getBytes());
            return response.writeWith(Mono.just(dataBuffer));
        }
    }

    //执行顺序
    @Override
    public int getOrder() {
        return 0;
    }
}
